<template>
  <div class="trade-company-map-container w-full h-full">
    <div class="map-header">
      <h3 class="text-lg font-bold text-white mb-3">全国外贸企业分布热力图</h3>
      <div class="legend">
        <div class="legend-item">
          <div class="legend-color" style="background: #1e3a8a"></div>
          <span>0-20万家</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #3b82f6"></div>
          <span>20-50万家</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #60a5fa"></div>
          <span>50-100万家</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #93c5fd"></div>
          <span>100-200万家</span>
        </div>
        <div class="legend-item">
          <div class="legend-color" style="background: #bfdbfe"></div>
          <span>200万家以上</span>
        </div>
      </div>
    </div>
    
    <div class="map-container">
      <div 
        ref="chinaMap" 
        class="china-map-chart"
        @mouseleave="handleMouseLeave"
      ></div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p class="loading-text">正在加载地图数据...</p>
      </div>
    </div>
    
    <!-- 省份详情弹窗 -->
    <div 
      v-if="selectedProvince && showTooltip" 
      class="province-detail"
      :style="{ left: tooltipX + 'px', top: tooltipY + 'px' }"
    >
      <div class="detail-header">
        <h4>{{ selectedProvince }}</h4>
        <button @click="closeTooltip" class="close-btn">×</button>
      </div>
      <div class="detail-content">
        <p>企业数量: {{ selectedProvinceData?.count || 0 }} 万家</p>
        <p>区域类别: {{ selectedProvinceData?.category || '暂无' }}</p>
        <p>发展水平: {{ getDevelopmentLevel(selectedProvinceData?.count) }}</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TradeCompanyMap',
  data() {
    return {
      chart: null,
      loading: true,
      selectedProvince: null,
      showTooltip: false,
      tooltipX: 0,
      tooltipY: 0,
      // 基于CSV数据的企业分布数据
      provinceData: {
        '广东省': { count: 245.5, category: '核心集聚区' },
        '浙江省': { count: 132.8, category: '核心集聚区' },
        '江苏省': { count: 128.6, category: '核心集聚区' },
        '上海市': { count: 98.7, category: '核心集聚区' },
        '福建省': { count: 86.4, category: '海峡经济区' },
        '山东省': { count: 78.9, category: '沿海发达区' },
        '北京市': { count: 65.2, category: '环渤海区' },
        '香港特别行政区': { count: 58.3, category: '国际枢纽' },
        '台湾省': { count: 52.1, category: '海峡经济区' },
        '四川省': { count: 42.3, category: '西部增长极' },
        '湖北省': { count: 38.7, category: '中部枢纽' },
        '河南省': { count: 36.5, category: '中部枢纽' },
        '湖南省': { count: 34.2, category: '中部枢纽' },
        '安徽省': { count: 32.8, category: '中部枢纽' },
        '辽宁省': { count: 29.4, category: '环渤海区' },
        '天津市': { count: 28.1, category: '环渤海区' },
        '河北省': { count: 26.7, category: '环渤海区' },
        '江西省': { count: 24.3, category: '中部枢纽' },
        '广西壮族自治区': { count: 22.5, category: '西部增长极' },
        '重庆市': { count: 20.8, category: '西部增长极' },
        '陕西省': { count: 19.2, category: '西部增长极' },
        '澳门特别行政区': { count: 18.6, category: '国际枢纽' },
        '云南省': { count: 17.6, category: '西部增长极' },
        '黑龙江省': { count: 15.3, category: '东北区' },
        '吉林省': { count: 14.1, category: '东北区' },
        '山西省': { count: 13.4, category: '中部枢纽' },
        '贵州省': { count: 11.8, category: '西部增长极' },
        '甘肃省': { count: 10.2, category: '西部增长极' },
        '海南省': { count: 9.7, category: '沿海发达区' },
        '内蒙古自治区': { count: 8.9, category: '北部边疆区' },
        '新疆维吾尔自治区': { count: 7.5, category: '西部边疆区' },
        '西藏自治区': { count: 5.2, category: '西部边疆区' },
        '宁夏回族自治区': { count: 4.8, category: '西部增长极' },
        '青海省': { count: 4.1, category: '西部增长极' }
      }
    }
  },
  computed: {
    selectedProvinceData() {
      return this.provinceData[this.selectedProvince]
    }
  },
  mounted() {
    this.initMap()
  },
  beforeUnmount() {
    if (this.chart) {
      this.chart.dispose()
    }
  },
  methods: {
    getDevelopmentLevel(count) {
      if (!count) return '数据缺失'
      if (count >= 200) return '极高水平'
      if (count >= 100) return '高水平'
      if (count >= 50) return '中高水平'
      if (count >= 20) return '中等水平'
      return '发展中'
    },
    
    async initMap() {
      try {
        // 动态加载 ECharts
        const echarts = await this.loadECharts()
        
        // 获取中国地图数据
        const chinaGeoData = await this.loadChinaMapData()
        
        // 注册地图
        echarts.registerMap('china', chinaGeoData)
        
        // 初始化图表
        this.chart = echarts.init(this.$refs.chinaMap, 'dark')
        
        // 配置图表选项
        const option = this.getMapOption()
        this.chart.setOption(option)
        
        // 绑定事件
        this.bindEvents()
        
        this.loading = false
      } catch (error) {
        console.error('地图初始化失败:', error)
        this.loading = false
      }
    },
    
    async loadECharts() {
      return new Promise((resolve, reject) => {
        if (window.echarts) {
          resolve(window.echarts)
          return
        }
        
        const script = document.createElement('script')
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/echarts/5.5.0/echarts.min.js'
        script.onload = () => resolve(window.echarts)
        script.onerror = reject
        document.head.appendChild(script)
      })
    },
    
    async loadChinaMapData() {
      const response = await fetch('https://geo.datav.aliyun.com/areas/bound/100000_full.json')
      if (!response.ok) {
        throw new Error('Failed to load map data')
      }
      return await response.json()
    },
    
    getMapOption() {
      // 准备数据
      const mapData = Object.keys(this.provinceData).map(name => ({
        name,
        value: this.provinceData[name].count
      }))
      
      return {
        backgroundColor: 'transparent',
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            const data = this.provinceData[params.name]
            if (!data) return `${params.name}<br/>暂无数据`
            return `
              <div style="font-size: 14px; line-height: 1.5;">
                <strong>${params.name}</strong><br/>
                企业数量: ${data.count} 万家<br/>
                区域类别: ${data.category}<br/>
                发展水平: ${this.getDevelopmentLevel(data.count)}
              </div>
            `
          }
        },
        geo: {
          map: 'china',
          roam: true,
          zoom: 1.2,
          center: [105, 36],
          itemStyle: {
            borderColor: '#404040',
            borderWidth: 1
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 20,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        },
        series: [
          {
            name: '外贸企业数量',
            type: 'map',
            map: 'china',
            zoom: 1.2,
            center: [105, 36],
            data: mapData,
            itemStyle: {
              borderColor: '#404040',
              borderWidth: 1
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ],
        visualMap: {
          left: 'left',
          top: 'bottom',
          type: 'piecewise',
          pieces: [
            { min: 200, color: '#1e3a8a' },
            { min: 100, max: 200, color: '#3b82f6' },
            { min: 50, max: 100, color: '#60a5fa' },
            { min: 20, max: 50, color: '#93c5fd' },
            { min: 0, max: 20, color: '#bfdbfe' }
          ],
          text: ['高', '低'],
          textStyle: {
            color: '#fff'
          },
          backgroundColor: 'rgba(0, 0, 0, 0.3)',
          borderColor: '#404040',
          borderWidth: 1,
          padding: [10, 10]
        }
      }
    },
    
    bindEvents() {
      // 鼠标悬浮事件
      this.chart.on('mouseover', (params) => {
        if (params.componentType === 'series') {
          this.selectedProvince = params.name
          this.showTooltip = true
          this.updateTooltipPosition(params.event.event)
        }
      })
      
      // 鼠标点击事件
      this.chart.on('click', (params) => {
        if (params.componentType === 'series') {
          this.selectedProvince = params.name
          this.showTooltip = true
          this.updateTooltipPosition(params.event.event)
        }
      })
      
      // 窗口大小变化事件
      window.addEventListener('resize', () => {
        if (this.chart) {
          this.chart.resize()
        }
      })
    },
    
    updateTooltipPosition(event) {
      const container = this.$refs.chinaMap
      const containerRect = container.getBoundingClientRect()
      
      this.tooltipX = event.clientX - containerRect.left + 10
      this.tooltipY = event.clientY - containerRect.top - 10
      
      // 确保弹窗不超出边界
      const tooltipWidth = 250
      const tooltipHeight = 150
      
      if (this.tooltipX + tooltipWidth > containerRect.width) {
        this.tooltipX = event.clientX - containerRect.left - tooltipWidth - 10
      }
      
      if (this.tooltipY + tooltipHeight > containerRect.height) {
        this.tooltipY = event.clientY - containerRect.top - tooltipHeight - 10
      }
    },
    
    handleMouseLeave() {
      // 延迟关闭弹窗，避免鼠标移动到弹窗时立即关闭
      setTimeout(() => {
        if (!this.$refs.chinaMap?.matches(':hover')) {
          this.showTooltip = false
        }
      }, 200)
    },
    
    closeTooltip() {
      this.showTooltip = false
      this.selectedProvince = null
    }
  }
}
</script>

<style scoped>
.trade-company-map-container {
  position: relative;
  width: 100%;
  height: 100%;
  background: transparent;
  border-radius: 8px;
  overflow: hidden;
}

.map-header {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  background: rgba(255, 255, 255, 0.05);
}

.legend {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: white;
  font-size: 12px;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 2px;
  border: 1px solid rgba(255, 255, 255, 0.3);
}

.map-container {
  position: relative;
  height: calc(100% - 70px);
  min-height: 300px;
}

.china-map-chart {
  width: 100%;
  height: 100%;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(255, 255, 255, 0.3);
  border-top: 3px solid #60a5fa;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

.loading-text {
  color: white;
  font-size: 14px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.province-detail {
  position: absolute;
  background: rgba(0, 0, 0, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 8px;
  padding: 15px;
  min-width: 200px;
  max-width: 300px;
  z-index: 1000;
  backdrop-filter: blur(10px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 8px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.detail-header h4 {
  color: #60a5fa;
  font-size: 16px;
  font-weight: bold;
  margin: 0;
}

.close-btn {
  background: none;
  border: none;
  color: #9ca3af;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 2px;
  transition: all 0.2s;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

.detail-content {
  color: white;
  font-size: 14px;
  line-height: 1.6;
}

.detail-content p {
  margin: 8px 0;
}

.detail-content p:first-child {
  margin-top: 0;
}

.detail-content p:last-child {
  margin-bottom: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .map-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
    padding: 12px 16px;
  }
  
  .legend {
    gap: 8px;
  }
  
  .legend-item {
    font-size: 11px;
  }
  
  .province-detail {
    min-width: 180px;
    max-width: 250px;
    padding: 12px;
  }
  
  .map-container {
    height: calc(100% - 80px);
  }
}
</style> 